iT邦幫忙

2024 iThome 鐵人賽

DAY 6
0

Day20 要來控制麥克風

資料設定

const SpeechRecognition =
  (window as any).SpeechRecognition || (window as any).webkitSpeechRecognition;
const recognition = new SpeechRecognition();

recognition.interimResults = true;
recognition.lang = "zh-TW";

  const [isListening, setIsListening] = useState(false);
  const [transcript, setTranscript] = useState("");

功能函式

  const handleResult = (event: SpeechRecognitionEvent) => {
    const current = event.resultIndex;
    const transcript = event.results[current][0].transcript;
    setTranscript((prev) => prev + transcript + " ");
  };

  const handleEnd = () => {
    if (isListening) {
      recognition.start();
    }
  };

  const startListening = useCallback(() => {
    setIsListening(true);
    setTranscript("");
    recognition.onresult = handleResult as EventListener;
    recognition.onend = handleEnd;
    recognition.start();
  }, []);

  const stopListening = useCallback(() => {
    setIsListening(false);
    recognition.stop();
  }, []);

畫面結構

  return (
    <div className="flex flex-col items-center justify-center min-h-screen bg-gray-100 p-4">
      <h1 className="text-3xl font-bold mb-4">Speech Detection</h1>

      <div className="w-full max-w-2xl bg-white rounded-lg shadow-md p-6">
        <div className="mb-4">
          <button
            type="button"
            onClick={isListening ? stopListening : startListening}
            className={`px-4 py-2 rounded-full font-semibold text-white ${
              isListening
                ? "bg-red-500 hover:bg-red-600"
                : "bg-blue-500 hover:bg-blue-600"
            }`}
          >
            {isListening ? "STOP" : "START"}
          </button>
        </div>

        <div className="bg-gray-100 p-4 rounded-lg min-h-[200px] whitespace-pre-wrap">
          {transcript || "Waiting for speech..."}
        </div>
      </div>
    </div>
  );

DEMO

https://codesandbox.io/p/devbox/day20-speech-detection-zl7p7x


上一篇
[Day19]_Webcam-Fun
下一篇
[Day21]_Geolocation
系列文
React30——用 React 探索 JavaScript30 的魅力30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言